package com.agency.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Lu.Bing on 16-6-23.
 *
 * @author Lu.Bing
 */
public class WideWebInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String fullPath = request.getServletPath();
        StringBuffer pathes = request.getRequestURL();
        String tempContextUrl = pathes.delete(pathes.length() - request.getRequestURI().length(), pathes.length()).append("/").toString();
        /*// 必须是局域网用户
        if (StringUtils.equals(tempContextUrl, "http://localhost:8080/")
                || StringUtils.equals(tempContextUrl, "http://192.168.2.138:8080/")) {*/
        HttpSession session = request.getSession(false);

        if (fullPath.contains("validationCard")) {
            return true;
        }

        // 必须已经登陆过, 或者访问login page
        if (session == null && !fullPath.contains("/login.htm")) {
            response.sendRedirect("login.htm");
            return false;
        } else if (session != null && session.getAttribute("current_user") != null) {
            return true;
        } else if (fullPath.contains("/login.htm")) {
            return true;
        } else if (!fullPath.contains("/login.htm")) {
            response.sendRedirect("login.htm");
            return false;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandler...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
